// Copyright 2011 The OnTheQuarter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package server

import (
	"appengine"
	"appengine/datastore"
	"fmt"
	"http"
	"regexp"
)

var nameTest = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_\-]+$`)

func init() {
	http.HandleFunc("/checkname/", checkname)
}

func checkname(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	name := r.URL.Path[len("/checkname/"):]

	if !nameTest.MatchString(name) {
		fmt.Fprintf(w, "{ \"valid\": false }\n")
		return
	}

	pkey := datastore.NewKey(c, "Person", name, 0, nil)
	count, err := datastore.NewQuery("Person").Ancestor(pkey).Count(c)
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}
	avail := count == 0

	fmt.Fprintf(w, "{ \"valid\": true, \"available\": %v }\n", avail)
}
